package com.kcyu.sfherp.timerTask;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kcyu.sfherp.config.MQTT.MqttSample;
import com.kcyu.sfherp.entity.CkSale;
import com.kcyu.sfherp.entity.CkSaleLine;
import com.kcyu.sfherp.entity.WecomPostData;
import com.kcyu.sfherp.service.CkService;
import com.kcyu.sfherp.service.WeComService;

import ch.qos.logback.classic.Logger;
import com.kcyu.sfherp.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@Configuration
@EnableScheduling
@Slf4j
public class timerTask {

    @Autowired
    private CkService ckService;

    @Autowired
    private WeComService weComService;

    @Autowired
    private RedisCache redisCache;

    private boolean init = false;
    @Scheduled(fixedRate = 10000)
    private void configureTasks() throws MqttException {
        log.info("定时任务执行------");

        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String today = format.format(date);

        if(!init) {
            log.info("初始化过程，将内容存进redis");
            List<CkSale> ckSales = ckService.queryTodayCkSale();
            log.info("cksales ---- : {}", ckSales);


            HashSet<CkSale> ckSales1 = new HashSet<>(ckSales);
            redisCache.deleteObject("ck-sales-cache:" + today);
            redisCache.setCacheSet("ck-sales-cache:" + today, ckSales1);
            init = true;
        } else {
            log.info("获取已缓存数据");
            Set<CkSale> cacheSet = redisCache.getCacheSet("ck-sales-cache:" + today);

            // 获取数据库的数据
            List<CkSale> ckSales = ckService.queryTodayCkSale();
            log.info("原单数: {}, 新单数: {}", cacheSet.size(), ckSales.size());
            if (ckSales.size() != cacheSet.size()) {
                log.info("检测到有新订单，原单数: {}, 新单数: {}", cacheSet.size(), ckSales.size());
                HashSet<CkSale> ckSales1 = new HashSet<>(ckSales);
                redisCache.deleteObject("ck-sales-cache:" + today);
                redisCache.setCacheSet("ck-sales-cache:" + today, ckSales1);
                HashMap<String, List<CkSale>> map = new HashMap<>();
                map.put("data", ckSales);
                String jsonString = JSONObject.toJSONString(map);
                MqttSample.connect();
                MqttSample.sendMessage("/sfhErp/newOrder", jsonString);
            }
        }

    }

}
